-- Leviathan (c) v.v.balashoff
-- TODO DEBUG
dofile('libs/print_r.lua')

dofile('src/script.lua')

local Class = require('leviathan/Class')
local Domain = require('leviathan/ECS/Domain')
local i18n = require('libs/i18n')
-- TODO DEBUG
local Log = require('leviathan/Log')

local filename = 'scripts/main.lua'

local ScriptSystem = Class:derive('CoreScriptSystem')

function ScriptSystem:new(domain)
    self.name = 'CoreScriptSystem'
    self.domain = domain
    self.enabled = false
end


function ScriptSystem:init(filename)
    local core, script
    Log:info('Core: Initializing script: '..filename)
    core = world:getDomain('Core')
    script = core:getEntity('ScriptComponent')
    script.filename = filename
    dofile(filename)
    script.enabled = true
end


function ScriptSystem:update(dt)
    local s = self.domain
    for _, c in pairs(s.entities) do
        if c.enabled then
            if c.componentType == 'ScriptComponent' then
                -- check initiate
                if not c.location then
                    Log:debug('Script: Missing current location. Walk to main...')
                    -- TODO
                    self:walk('main')
--                    self:walk('intro_001')
                end
            end
        end
    end
end


function ScriptSystem:walk(location)
-- TODO remove
--    Log:debug('Walking to location: '..location)
    local core = world:getDomain('Core')
    local script = core:getEntity('ScriptComponent')
    -- is it same location?
    if not (script.location == location) then
        local scr = base.screens[location]
        if scr.screen then
            -- create new domain
            local splash = world:createDomain('SplashScreen', location)
            world:addDomain(splash, 300)
            -- delete old domain
            world:deleteDomain(script.location)
            script.location = location
        else
            -- TODO доработать
print('HERE: ScriptSystem:walk TODO!')
        end
    end
end


return ScriptSystem
